﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.FileProviders;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using YShop.Contracts.Excel;
using YShop.Excel.Contracts;

namespace YShop.Excel
{
    public class ExcelService : IExcelService, IDynamicApiController, ISingleton
    {
        public void Load(string path)
        {
        }

        public void LoadSeed(string directory)
        {
            var files = Directory.GetFiles(directory);
            foreach(var file in files)
            {
            }

        }

        /// <summary>
        /// 读取到DataTable
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public object ReadToDataTable([FromQuery] ExcelReadConfig config)
        {
            ISheet sheet = null;
            using (FileStream file = new FileStream(config.Path, FileMode.Open, FileAccess.Read))
            {
                if (!config.Path.Contains(".xlsx", StringComparison.CurrentCulture))//2003
                {
                    HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);
                    sheet = hssfworkbook.GetSheetAt(0);
                }
                else//2007
                {
                    XSSFWorkbook xssfworkbook = new XSSFWorkbook(file);
                    sheet = xssfworkbook.GetSheetAt(0);
                }
            }

            IRow headerRow = sheet.GetRow(config.ColumnRowIndex);
            int cellCount = headerRow.LastCellNum;

            var columns = new List<string>();
            var result = new List<Dictionary<string, object>>();

            for (int j = 0; j < cellCount; j++)
            {
                ICell cell = headerRow.GetCell(j);
                columns.Add(cell.ToString());
            }

            for (int i = config.ColumnRowIndex + 1; i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                var dictObject = new Dictionary<string,object>();
                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    var cell = row.GetCell(j);
                    if (cell != null)
                    {
                        dictObject[columns[j]] = cell.ToString();
                    }
                    else
                    {
                        dictObject[columns[j]] = null;
                    }
                }
                result.Add(dictObject);

            }
            return result;
        }
    }
}
